<script setup>
    import {ref,reactive,toRefs,defineEmits} from 'vue'
    import bwPowerSet from '@/utils/power-set.js'
    import { showSuccessToast, showFailToast } from 'vant'
    import cartItemApi from '@/api/cart/cartItem'
    import {useRouter} from 'vue-router'
    const router = useRouter()

    const props = defineProps({
        product: Object,
        handle: String
    })
    const {product,handle} = toRefs(props)
    const data = reactive({
        price: 0,
        quantity: 1
    })

    //规格重组，status控制规格状态
    let specs = ref([...product.value.specifications])
    const skuStocks = product.value.skuStocks
    specs.value = specs.value.map(item => {
        return {
            spec: item.spec,
            values: item.value.split(';').map(val => {
                return {
                    value: val,
                    status: 0
                }
            })
        }
    })

    console.log(specs.value)

    //0：未选中   1：选中   2：禁用
    const clickSpec = (val,values) => {
        if(val.status === 2){
            //如果是禁用状态，则跳过
            return
        }else if(val.status === 1){
                //如果是选中，则改为未选中
            val.status = 0
        }else{
            //如果是未选中，则改为选中，兄弟节点 改为 未选中
            values.forEach(e => e.status = 0)
            val.status = 1
        }

        //更新其他节点的状态
        updateStatus()

        //展示规格组合的最新价格
        showPrice()
    }

    //生成组合字典
    const createPathDict = () => {
        const pathDict = []

        skuStocks.forEach(skuStock => {
            if (skuStock.stock === 0) {
                return
            }
            //幂集
            // 大一匹;单冷空调
            // []
            // [大一匹]
            // [单冷空调]
            // [大一匹,单冷空调]
            const powerSet = bwPowerSet(skuStock.sku.split(';'))
            console.log(skuStock.sku)
            console.log(powerSet)
            powerSet.forEach(item => {
                if(item.length === 0){
                    return
                }else {
                    const path = item.join(';')
                    pathDict.push(path)
                }
            })
        })

        console.log('pathDict',pathDict)
        return pathDict
    }

    createPathDict()

    //更新其他节点的状态
    //用户比如选择了1个
    const updateStatus = () => {
        //获取用户选中了哪些规格
        const selectedArr = getSelectedArr()
        console.log('selectedArr',selectedArr)

        //将将来有可能选择的状态进行修改
        specs.value.forEach((item,index) => {
            //潜在的规格组合
            const _selectedArr = [...selectedArr]

            item.values.forEach(it => {
                if(it.status === 1){
                    //如果节点选中的话，跳过
                    return
                }else {
                    _selectedArr[index] = it.value
                    //比如：当点击55英寸后，_selectedArr就有可能为['60英寸','',''],['55英寸','k9','']等
                    console.log('_selectedArr',_selectedArr)
                }
                const key = _selectedArr.filter(v => v).join(';')

                //去字典查看是否存在
                const pathDict = createPathDict()
                if (pathDict.indexOf(key) < 0) {
                    //不存在，禁用
                    it.status = 2
                }else {
                    it.status = 0
                }
            })
        })

    }

    //获取用户选中了哪些规格
    const getSelectedArr = () => {
        return specs.value.map(item => {
            const spec = item.values.find(it => it.status === 1)
            return spec ? spec.value : ''
        })
    }

    //展示规格组合的最新价格
    const showPrice = () => {
        //获取用户选中了哪些规格
        const selectedArr = getSelectedArr()
        const skuStock = skuStocks.find(item => item.sku === selectedArr.join(';'))
        if (skuStock) {
            data.price = skuStock.price
        }else {
            data.price = product.value.price
        }
    }

    showPrice()
    updateStatus()

    const emits = defineEmits(['closeSkuShow'])

    const handleSubmit = () => {
        //获取用户选中了哪些规格
        const selectedArr = getSelectedArr().filter(v => v)
        if(specs.value.length != selectedArr.length){
            showFailToast('请选择规格')
            return
        }
        const skuStock = skuStocks.find(item => item.sku === selectedArr.join(';'))
        const skuId = skuStock.id
        console.log('skuId',skuId)

        if(handle.value === 'cart'){
            //加入购物车
            cartItemApi.addCartItem({
                productId: product.value.id,
                skuId: skuId,
                quantity: data.quantity
            }).then(response => {
                showSuccessToast('已加入购物车')
                emits('closeSkuShow')
            })
        }else {
            //立即购买
            router.push({
                name: 'OrderPreview',
                query: {
                    productId: product.value.id,
                    skuId: skuId,
                    quantity: data.quantity
                }
            })

        }

    }
</script>

<template>
	<div class="spec">

		<div>
			<van-image width="100" height="100" :src="product.image"/>
			<span class="price">￥ {{data.price}}</span>
			<span>请选择规格</span>
		</div>

		<div v-for="item in specs"><!---->
			<div class='title'>{{item.spec}}</div>
			<div class='spec-items'>

				<div class='spec-item' v-for="val in item.values"><!---->
					<span v-if="val.status === 0" @click="clickSpec(val,item.values)" class="">{{val.value}}</span>
                    <span v-if="val.status === 1" @click="clickSpec(val,item.values)" class="active">{{val.value}}</span>
                    <span v-if="val.status === 2" class="disabled">{{val.value}}</span>
				</div>
			</div>
		</div>

		<div>
			<div class='title'>数量</div>
			<van-stepper v-model="data.quantity" />
		</div>

		<div style="margin: 16px;">
			<van-button round block type="primary" native-type="submit" @click="handleSubmit">确定</van-button>
		</div>

	</div>

</template>

<style scoped>
	.spec {
		font-size: 14px;
		padding: 16px;
	}

	.spec .price {
		font-size: 21px;
		font-weight: bold;
		color: rgb(234, 19, 19);
		margin: 0 10px;
	}

	.title {
		line-height: 40px;
	}

	.spec-item {
		display: inline-block;
		margin-right: 10px;
	}

	.spec-item span {
		border: 1px solid #eee;
		cursor: pointer;
		padding: 5px 10px;
	}

	.spec-item .active {
		border: 1px solid red;
		background-color: red;
		color: #fff;
	}

	.spec-item .disabled {
		color: #c0c4cc;
		cursor: not-allowed;
		background-image: none;
		background-color: #fff;
		border-color: #ebeef5;
	}
</style>
